package cn.bone.mqtt.demo01;

import com.alibaba.fastjson.JSON;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * Created by MD-01 on 2017/4/19.
 */
public class Server {

    //public static final String host = "tcp://127.0.0.1:1883";
    public static final String host = "tcp://iot.eclipse.org:1883";
    public static final String TOPIC = "toclient/124";
    public static final String TOPIC125 = "toclient/125";

    private String clientid = "server";
    private MqttClient client;
    private MqttTopic topic;
    private MqttTopic topic125;
    private String username = "admin";
    private String password = "admin";

    private Logger logger = LoggerFactory.getLogger("server");

    private MqttMessage message;

    public Server(){
        try {
            client = new MqttClient(host,clientid,new MemoryPersistence());
            connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void connect() throws MqttException {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        //设置超时时间
        options.setConnectionTimeout(10);
        //设置会话心跳
        options.setKeepAliveInterval(20);
        options.setWill("serverWill","server over".getBytes(),2,true);

        client.setCallback(new PushCallback());
        client.connect(options);
        topic = client.getTopic(TOPIC);
        topic125 = client.getTopic(TOPIC125);

    }

    public void publish(MqttTopic topic,MqttMessage message) throws MqttException {
        MqttDeliveryToken token = topic.publish(message);
        //阻塞直到消息发送完成
        token.waitForCompletion();
        logger.info("message is published completely! " + token.isComplete());
    }

    public static void main(String[] args){

        Server server = new Server();
        server.message = new MqttMessage();
        server.message.setQos(2);
        //是否保存消息
        server.message.setRetained(true);
        try {
            server.message.setPayload("给客户端124推送消息7".getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            server.publish(server.topic,server.message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
